﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Caliburn.Micro;
using Microsoft.Phone.Controls;
using Phone.Framework.Behaviors;
using System.Linq;
using System.Threading;
using Phone.Framework.Threads;
using Phone.Framework.CaliburnExtensions.Results;
using System.Collections.Generic;
namespace Phone.Framework
{
    public interface IMediaPlayService
    {
        void Play(string soruceUrl, System.Action action);

        void Play(string[] soruceUrls,int index);
    }

    public static class InteractionExtension
    {
        public static T GetBehavior<T>(this DependencyObject obj)
        {
            return System.Windows.Interactivity.Interaction.GetBehaviors(obj).OfType<T>().FirstOrDefault();
        }

        public static T GetTrigger<T>(this DependencyObject obj)
        {
            return System.Windows.Interactivity.Interaction.GetTriggers(obj).OfType<T>().FirstOrDefault();
        }
    }

    public class MediaPlayService : IMediaPlayService
    {
        private readonly INavigationService _navigationService;
        public MediaPlayService(INavigationService navigationService)
        {
            _navigationService = navigationService;
        }

        public void Play(string sourceUrl, System.Action action)
        {
            var page = _navigationService.CurrentContent as PhoneApplicationPage;
            var behavior = page.GetBehavior<MediaPlayBehavior>();
            behavior.Play(sourceUrl, action);
        }

        public void Play(string[] sourceUrls,int index)
        {
            if (index == sourceUrls.Length) return;
            var page = _navigationService.CurrentContent as PhoneApplicationPage;
            var behavior = page.GetBehavior<MediaPlayBehavior>();

            behavior.Play(sourceUrls[index], () =>
            {
                //Thread.SpinWait(300);
                Play(sourceUrls, ++index);
            });
           //Coroutine.BeginExecute(soruceUrls.Select(e=>new ActionResult((IActionResult r) => {
           //    UIThread.Invoke(() => {
           //        behavior.Play(e, () =>
           //        {
           //            r.Set();
           //        });
           //    });

           // })).Cast<IResult>().GetEnumerator());
            //IList<IResult> list = new List<IResult>();
            //list.Add(action);
            //Coroutine.BeginExecute(list.GetEnumerator());

            //ResultHelper.Execute(new ActionResult((IActionResult r) => {
            //    behavior.Play(soruceUrls[0], () =>
            //    {
            //        r.Set();
            //    });
            //}));
           
        }
    }
}
